<?php

namespace App\Service\Sign;

use App\Dao\Sign\SignTaskDao;
use App\Dao\Sign\SignTaskLogDao;
use App\Dao\User\UserDao;
use App\Model\Sign\SignTask;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Collection;

class SignTaskService extends BaseService
{

    /**
     * @Inject()
     * @var SignTaskDao
     */
    protected $signTaskDao;

    /**
     * @Inject()
     * @var SignTaskLogDao
     */
    protected $signTaskLogDao;

    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;

    public function lists(Collection $params,$user_id=0)
    {


        $data = $this->signTaskDao->params($params)->getList();

        if ($user_id) {

            $data->transform(function ($data) use ($user_id) {
                $finish = $this->signTaskLogDao->getFinishedNum($user_id, $data->code);
                $data->finish = $finish;
                $receive_status = 0;
                if ($finish >= $data->times) {
                    $receive_status = 1;
                }
                if ($this->signTaskDao->isReceive($user_id, $data->code)) {
                    $receive_status = 2;
                }
                $data->receive_status = $receive_status;
                return $data;
            });
        }


        return $data;
    }

    public function edit(int $id, \Hyperf\Utils\Collection $data)
    {
        $data = $this->signTaskDao->edit($id, $data);
        return $data;
    }

    public function receive($userId, $code)
    {
        //receive
        $isReceive = $this->signTaskDao->isReceive($userId, $code);
        if ($isReceive) {
            _Error('已经领取了');
        }
        /** @var SignTask $signTask */
        $signTask = $this->signTaskDao->where('code', $code)->firstOrError();
        //finish
        $finishNum = $this->signTaskLogDao->getFinishedNum($userId, $code);
        if ($signTask->times > $finishNum) {
            _Error('未完成');
        }
        $point = $signTask->point;
        $this->userDao->opAccount('integral', $userId, $point, 'sign_task', $code);
        return true;
    }

    public function do($userId, $code)
    {
        return $this->signTaskLogDao->create([
            'user_id' => $userId,
            'code' => $code
        ]);
    }


    public function setFieldStatus(int $id, string $field, int $value)
    {
        return $this->signTaskDao->setField($id, $field, $value);
    }

}